package controllers;

import com.google.gson.JsonObject;
import constants.Default;

import duppentity.dto.bu.BuDtoUtil;
import duppentity.dto.bu.CouponUserDto;
import play.Logger;
import utils.DateUtils;

import java.util.List;

/**
 * @author yangzhi
 * @date 2019/1/21
 */
public class ExportExcelController extends ApiController {

	/**
	 * 导出优惠券列表
	 */
	public static void exportCouponList(){
		Long couponId = params.get("couponId", Long.class);
		//day 日导出，month 月导出
		String type = params.get("type", String.class);
		String startCreateTime = "";
		String endCreateTime = "";
		JsonObject data = new JsonObject();
		if (type.equals("day")) {
			//按日导出
			String ymd = params.get("time", String.class);
			startCreateTime = DateUtils.formatDateToString(DateUtils.getStartOfDay(DateUtils.formatStrToDate(ymd, "yyyy-MM-dd")), "yyyy-MM-dd HH:mm:ss");
			endCreateTime = DateUtils.formatDateToString(DateUtils.getEndOfDay(DateUtils.formatStrToDate(ymd, "yyyy-MM-dd")), "yyyy-MM-dd HH:mm:ss");
			data = merchantDupp.getCouponUserList(null, null, couponId, startCreateTime, endCreateTime, null, null, null, null, 0, Default.PAGE_MAX_COUNT);
		} else if (type.equals("month")) {
			//按月导出
			String ym = params.get("time", String.class);
			startCreateTime = DateUtils.formatDateToString(DateUtils.getStartOfDay(DateUtils.formatStrToDate(DateUtils.getFirstDay(ym + "-01"), "yyyy-MM-dd")), "yyyy-MM-dd HH:mm:ss");
			endCreateTime = DateUtils.formatDateToString(DateUtils.getEndOfDay(DateUtils.formatStrToDate(DateUtils.getLastDay(ym + "-01"), "yyyy-MM-dd")), "yyyy-MM-dd HH:mm:ss");
			data = merchantDupp.getCouponUserList(null, null, couponId, null, null, startCreateTime, endCreateTime, null, null, 0, Default.PAGE_MAX_COUNT);
		}

		if (!checkResult(data)) {
			apiError(data);
		}
		Integer total = data.get("total").getAsInt();

		List<CouponUserDto> couponUserDtoList = BuDtoUtil.getCouponUserDtoList(data);
		//循环获取搜索结果
		if (total > Default.PAGE_MAX_COUNT) {
			Integer countPage = total % Default.PAGE_MAX_COUNT == 0 ? total / Default.PAGE_MAX_COUNT : total / Default.PAGE_MAX_COUNT + 1;
			for (Integer i = 1; i < countPage; i++) {
				JsonObject pageData = new JsonObject();
				Integer offset = i * Default.PAGE_MAX_COUNT;
				if (type.equals("day")) {
					pageData = merchantDupp.getCouponUserList(null, null, couponId, startCreateTime, endCreateTime, null, null, null, null, offset, Default.PAGE_MAX_COUNT);
				} else if (type.equals("month")) {
					pageData = merchantDupp.getCouponUserList(null, null, couponId, null, null, startCreateTime, endCreateTime, null, null, offset, Default.PAGE_MAX_COUNT);
				}
				if (!checkResult(pageData)) {
					Logger.info("exportCouponList:" + i + 1 + "页错误了");
					apiError(pageData);
				}
				List<CouponUserDto> pageList = BuDtoUtil.getCouponUserDtoList(pageData);
				if (pageList.size() > 0) {
					couponUserDtoList.addAll(pageList);
				}
			}
		}
		apiList(data, couponUserDtoList);
	}
}
